import 'dart:convert';
import 'package:http/http.dart' as http;

class NetworkHelper {
  //注册
  Future<dynamic> register({
    required String email,
    required String password,
  }) async {
    Uri uri = Uri.parse('http://192.168.2.14:3000/register');
    try {
      var response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'email': email, 'password': password}),
      );
      if (response.statusCode == 200) {
        String body = response.body;
        print('注册成功: $body');
        var decode = jsonDecode(body);
        return decode;
      } else {
        print('注册失败，响应码: ${response.statusCode}, 详情: ${response.body}');
      }
    } catch (e) {
      print('网络请求错误: $e');
    }
  }

  //登录
  Future<dynamic> login({
    required String email,
    required String password,
  }) async {
    Uri uri = Uri.parse('http://192.168.2.14:3000/login');
    try {
      var response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'email': email, 'password': password}),
      );
      if (response.statusCode == 200) {
        String body = response.body;
        print('登录成功: $body');
        var decode = jsonDecode(body);
        return decode;
      } else {
        print('登录失败，响应码: ${response.statusCode}, 详情: ${response.body}');
      }
    } catch (e) {
      print('网络请求错误: $e');
    }
  }

  //发送消息
  Future<dynamic> sendMessage({
    required String sender,
    required String text,
  }) async {
    Uri uri = Uri.parse('http://192.168.2.14:3000/sendMessage');
    try {
      var response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'sender': sender, 'text': text}),
      );
      if (response.statusCode == 200) {
        String body = response.body;
        print('发送成功: $body');
        var decode = jsonDecode(body);
        return decode;
      } else {
        print('发送失败，响应码: ${response.statusCode}, 详情: ${response.body}');
      }
    } catch (e) {
      print('网络请求错误: $e');
    }
  }

  //获取消息列表数据
  Future<List<dynamic>> messageList() async {
    Uri uri = Uri.parse('http://192.168.2.14:3000/messageList');
    try {
      var response = await http.get(uri);
      if (response.statusCode == 200) {
        String body = response.body;
        var decode = jsonDecode(body);
        print('获取成功: ${decode['messages']}');
        return decode['messages']; // 直接返回 messages 列表
      } else {
        print('获取失败，响应码: ${response.statusCode}, 详情: ${response.body}');
        return []; // 返回空列表表示失败
      }
    } catch (e) {
      print('网络请求错误: $e');
      return []; // 返回空列表表示错误
    }
  }
}
